import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:jetour_line/aha_jetour_line.dart';
import 'package:jetour_line/aha_manger.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/base_widget/loading_widget.dart';
import 'package:jetour_line/base_widget/my_refresh_view.dart';
import 'package:jetour_line/model/line_detail_model.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/network/jetour_http.dart';
import 'package:jetour_line/pages/baseWidget/bottom_widget.dart';
import 'package:jetour_line/pages/baseWidget/title_widget.dart';
import 'package:jetour_line/pages/line/lineDetail/line_detail_budget_widget.dart';
import 'package:jetour_line/pages/line/lineDetail/line_detail_head_widget.dart';
import 'package:jetour_line/pages/line/lineDetail/line_detail_introduce_list_widget.dart';
import 'package:jetour_line/pages/line/lineDetail/line_detail_map_widget.dart';
import 'package:jetour_line/pages/line/lineDetail/line_detail_trip_list_widget.dart';
import 'package:jetour_line/utils/extension_int.dart';
import '../../../base_widget/my_alert.dart';
import '../../../base_widget/sliver_list_widget.dart';
import '../../../model/line_list_model.dart';
import '../../../network/aha_http.dart';

class LineDetailPageScreen extends StatefulWidget {
  final int id;
  Function? collectCallBack;
   LineDetailPageScreen({Key? key, required this.id,this.collectCallBack}) : super(key: key);

  @override
  State<LineDetailPageScreen> createState() => _LineDetailPageScreenState();
}

class _LineDetailPageScreenState extends State<LineDetailPageScreen> {
  final MyRefreshViewController _controller = MyRefreshViewController();
  LineDetailModel? _lineDetailModel;
  late List<LineListlModel> abouRoutList; //相关路书推荐数据

  bool selTrip = false;
  bool isCollect = false;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getDetailMsg();
    MapUtils.getMaps();
  }

  void login(String msg) {
    print("LoginCallBack = LoginCallBack  msg = $msg");
  }


  Future<bool> _onWillPop() async {
    if(widget.collectCallBack!= null){
      widget.collectCallBack!(isCollect);
    }
    Navigator.pop(context);
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Platform.isIOS
        ? GestureDetector(
      onHorizontalDragUpdate: (details) {
        if (details.delta.dx > 0) {
          _onWillPop!.call();
        }
      },
      child: WillPopScope(
        onWillPop: _onWillPop,
        child: getBodyWidget(),
      ),
    )
        : WillPopScope(
      onWillPop: _onWillPop,
      child: getBodyWidget(),
    );
  }

  Widget getBodyWidget(){
    return  BaseScaffold(
        title: "路书详情",
        leftItemCallBack: (){
          if(widget.collectCallBack!= null){
            widget.collectCallBack!(isCollect);
          }
          Navigator.pop(context);
        },
        backgroundColor: Colors.white,
        // ignore: unnecessary_null_comparison
        body: SafeArea(
          child: _lineDetailModel == null
              ? SizedBox()
              : Column(
            children: [
              Expanded(
                  child: CustomScrollView(
                    //页面复杂Listview
                    slivers: [
                      LineDetailHeadWidget(
                          lineDetailModel: _lineDetailModel!),
                      LineDetailMapWidget(lineDetailModel: _lineDetailModel!),
                      SliverListWidget.getSliverContainer(
                          80.px,
                          TitleWidget(
                            const ['介绍', '行程'],
                            selectIndexCallBack: (index) {
                              if (selTrip && index == 1) {
                                return;
                              }
                              if (!selTrip && index == 0) {
                                return;
                              }
                              if (index == 0) {
                                selTrip = false;
                              } else {
                                selTrip = true;
                              }
                              setState(() {});
                            },
                          )),
                      SliverPadding(
                        padding: EdgeInsets.only(top: 30.px),
                        sliver: LineDetailTripListWidget(
                          lineDetailModel: _lineDetailModel!,
                          selTrip: selTrip,
                          callBack: () {
                            buyLine();
                          },
                        ),
                      ),
                      SliverListWidget.getSliverList(1, (context, index) {
                        return Column(
                          children: [
                            Container(
                              width: double.infinity,
                              height: 46.px,
                              color: MyColors.white,
                            ),
                            Container(
                              width: double.infinity,
                              height: 24.px,
                              color: MyColors.colorF1F1F1,
                            ),
                            Row(
                              children: [
                                SizedBox(
                                  width: 24.px,
                                  height: 88.px,
                                ),
                                Expanded(
                                    child: Text("预算清单",
                                        style: TextStyle(
                                            fontSize: 32.px,
                                            color: MyColors.color1A1A1A,
                                            fontWeight: FontWeight.w500))),
                                BaseImage(
                                  image: 'ls_icon_notes',
                                  width: 40.px,
                                  height: 40.px,
                                ),
                                Text("以下价格仅作参考",
                                    style: TextStyle(
                                        fontSize: 28.px,
                                        color: MyColors.color999999)),
                                SizedBox(
                                  width: 24.px,
                                  height: 88.px,
                                ),
                              ],
                            )
                          ],
                        );
                      }),
                      LineDetailBudgetWidget(
                          lineDetailModel: _lineDetailModel!),
                    ],
                  )),
              Container(
                color: MyColors.white,
                width: double.infinity,
                height: 116.px,
                child: Row(
                  children: [
                    Expanded(
                      child: BottomWidget(
                        type: 1,
                        typeId: _lineDetailModel!.id!,
                        shareTitle: _lineDetailModel!.caption!,
                        shareSubTitle: _lineDetailModel!.description!,
                        shareImgUrl:
                        _lineDetailModel!.swiper!.first!.url!,
                        fav: _lineDetailModel!.otherData!.isFav!,
                        callBack: () {
                          _getRoutDetail();
                        },
                        collectCallBack: (bool isc){
                          isCollect = isc;
                        },
                      ),
                    ),
                    if (_lineDetailModel!.needBuy!)
                      GestureDetector(
                        onTap: () {
                          buyLine();
                        },
                        child: Padding(
                          padding:
                          EdgeInsets.only(left: 20.px, right: 20.px),
                          child: ClipRRect(
                            borderRadius:
                            BorderRadius.all(Radius.circular(58.px)),
                            child: Container(
                              width: 300.px,
                              height: 80.px,
                              color: MyColors.color00A198,
                              alignment: Alignment.center,
                              child: Text(
                                "购买路书",
                                style: TextStyle(
                                    fontSize: 30.px,
                                    color: MyColors.white,
                                    fontWeight: FontWeight.w500),
                              ),
                            ),
                          ),
                        ),
                      )
                  ],
                ),
              )
            ],
          ),
        ));
  }

  ///购买路书
  Future<void> buyLine() async {
    Map<String, dynamic> params = {};
    params["id"] = widget.id;
    var value = await AhaHttp().post(AhaRouter.LineCreatOrder, data: params);
    if (value != null) {



      String orderId = value['orderId'];
      if (orderId != null) {
        if(AhaManger().isUat){
          MapUtils.buyLine(
              'http://devrestapi.ahatrip.net/v3/open/order/pay-prefix?orderId=$orderId');
        }else{
          MapUtils.buyLine(
              'https://restapi.ahatrip.net/v3/open/order/pay-prefix?orderId=$orderId');
        }
        // ignore: use_build_context_synchronously
        showMyDialog(context, '是否支付成功', "是", "否", (index) {
            _getDetailMsg();
        });
      }
    } else {}
  }

  ///等待多个异步请求 全部完成
  void _getDetailMsg() async {
    _getRoutDetail();
    // var result = await Future.wait([
    //   // _getRoutDetail(),
    //   // _getSimilarLine(),
    // ]);
    // setState(() {});
  }

  ///获取路书详情
  Future _getRoutDetail() async {
    Map<String, dynamic> params = {};
    params["id"] = widget.id;
    var value = await AhaHttp().get(AhaRouter.LineLinedetail, params: params);

    if (value != null) {
      _lineDetailModel = LineDetailModel.fromJson(value);
      setState(() {});
    } else {

    }
  }
}
